package com.lam.system.controller;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.LoginUser;
import com.lam.common.base.domain.Result;
import com.lam.common.components.dict.DictCacheUtils;
import com.lam.common.components.dict.DictUtil;
import com.lam.common.components.dict.constant.DictTypeEnum;
import com.lam.common.components.dict.model.DictDesc;
import com.lam.common.components.file.FileDownloadUtil;
import com.lam.common.components.file.model.FileDownloadInfo;
import com.lam.common.components.file.model.FileBusiTypeEnum;
import com.lam.common.config.AppBaseConfig;
import com.lam.common.constant.CommonConstant;
import com.lam.common.context.TokenUtils;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.DateUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.StringUtils;
import com.lam.common.utils.UriSchemeUtil;
import com.lam.common.utils.uuid.IdGen;
import com.lam.common.validate.ValidateUtil;
import com.lam.common.validate.group.UpdateProfile;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.system.entity.SysUser;
import com.lam.system.param.SysUserParam;
import com.lam.system.service.SysUserService;

/**
 * 用户Controller
 * 
 * @author admin
 * @date 2022-08-04
 */
@Log(title = "个人信息")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/sys/userInfo")
public class UserInfoController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 当前用户信息
     */
	@Log(oper="当前用户信息")
    @GetMapping
    public Result getInfo() {
    	
		LoginUser loginUser = TokenUtils.getLoginUser();
    	SysUser sysUser = sysUserService.selectById(loginUser.getUserId());
    	Object userInfo = DictUtil.convertSimpleObject(sysUser);
    	userInfo = JsonUtil.mappingConvert(userInfo, "id=>userId", "username","realname","nickName","sex","sexDictText","email","phone", "post", "createTime");
    	Map<String, Object> userMap = JsonUtil.parseJSON(userInfo);
    	DictUtil.convertObject(userMap, new DictDesc("post", "sysPosts", DictTypeEnum.TABLE_DICT), 
    			new DictDesc("userId", "convertUserDepts", DictTypeEnum.TABLE_DICT).targetField("deptName"));
    	userMap.put("loginTime", DateUtil.formatDateTime(new Date(loginUser.getLoginTime())));
    	
    	Set<Object> roleCodeSet = TokenUtils.getLoginUserRoles();
    	Map<String, String> roleDictMap = DictCacheUtils.getTableDictMap("sysRoles");
    	String roleGroup = CollectionUtil.isEmpty(roleCodeSet)||CollectionUtil.isEmpty(roleDictMap)?"":
    		roleCodeSet.stream().map(t->roleDictMap.get(t)).filter(t->StringUtils.isNotBlank(t)).collect(Collectors.joining("，"));
    	
    	Map<String, Object> json = new HashMap<>();
    	json.put("user", userMap);
    	json.put("roleGroup", roleGroup);
        return Result.ok(json);
    }
    
    @Log(oper = "更改用户头像", businessType = BusinessType.UPDATE, saveReqData = false)
    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestBody SysUserParam userParam) {
    	
    	ValidateUtil.validRequired(userParam.getAvatarBase64(), "avatarBase64不能为空！");
    	
        // 获取token缓存中的用户对象
        LoginUser loginUser = TokenUtils.getLoginUser();
        // 文件名
        String fileName = DateUtil.getDate(DateUtil.PATTERN_YYYYMMDDHHMMSS_SSS) + IdGen.genRandom(4);
        fileName = CommonConstant.RESOURCE_PREFIX + File.separator + loginUser.getUserId() + File.separator + fileName;
        String filePath = UriSchemeUtil.convert2File(userParam.getAvatarBase64(), AppBaseConfig.me().getAvatarPath(), fileName);
        FileDownloadInfo downloadInfo = FileDownloadUtil.createDownloadInfo(FileBusiTypeEnum.AVATAR, filePath);
        sysUserService.updateAvatar(loginUser.getUserId(), downloadInfo.getS());
        
        // 重新设置token中的loginUser
        loginUser.setAvatar(downloadInfo.getS());
        TokenUtils.setLoginUser(loginUser);
        return Result.ok(downloadInfo);
    }
    
    /**
     * 修改用户
     */
    @Log(businessType = BusinessType.UPDATE, oper = "修改个人信息")
    @PutMapping
    public Result edit(@Validated(UpdateProfile.class) @RequestBody SysUser user) {
    
    	SysUser sysUser = new SysUser();
    	sysUser.setId(TokenUtils.getLoginUserid());
    	sysUser.setNickName(user.getNickName());
    	sysUser.setEmail(user.getEmail());
    	sysUser.setPhone(user.getPhone());
    	sysUser.setSex(user.getSex());
    	sysUser.setUpdateTime(user.getUpdateTime());
    	sysUser.setUpdateBy(user.getUpdateBy());
    	sysUserService.update(sysUser);
        return Result.ok();
    }
    
    /**
     * 重置密码
     */
    @Log(businessType = BusinessType.UPDATE, oper = "修改密码")
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody SysUserParam param) {
    	
    	ValidateUtil.validRequired(param.getOldpassword(), "请输入旧密码！");
    	ValidateUtil.validRequired(param.getPassword(), "请输入新密码！");
    	
    	return toAjax(sysUserService.updatePwd(param));
    }

}
